package us.nchu.tomtiger.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import us.nchu.tomtiger.enums.ResultEnum;
import us.nchu.tomtiger.model.Admin;
import us.nchu.tomtiger.model.Result;
import us.nchu.tomtiger.model.User;
import us.nchu.tomtiger.service.AdminService;
import us.nchu.tomtiger.service.UserService;
import us.nchu.tomtiger.utils.ResultUtil;
import us.nchu.tomtiger.utils.UserUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

/**
 * Created by XiongXuan on 2018/1/4.
 */
@Controller
@RequestMapping("/login")
public class LoginController {
    @Resource
    private UserService userService;
    @Resource
    private AdminService adminService;

    @GetMapping
    // 获取登录页面
    public ModelAndView doGet(HttpServletRequest httpServletRequest) {
        return new ModelAndView("login");
    }

    @PostMapping
    @ResponseBody
    // 登录
    public Result doPost(HttpServletRequest httpServletRequest) throws UnsupportedEncodingException {
        // 获取传入的注册参数
        String phoneNumber = httpServletRequest.getParameter("phoneNumber");
        String passwd = httpServletRequest.getParameter("password");

        User user = null;
        // 根据手机号码查询
        try {
            user = userService.getUserByPhoneNumber(phoneNumber);
        }catch (EmptyResultDataAccessException e) {
            // 没查询到
            return ResultUtil.getNoObjectInstance(ResultEnum.ERROR_LOGIN_NO_PHONENUMBER);
        }

        // 密码错误
        if (!user.getPassword().equals(passwd)) {
            return ResultUtil.getNoObjectInstance(ResultEnum.ERROR_LOGIN_WRONG_PASSWORD);
        }

        // 将用户信息写入状态
        UserUtil.writeUserInfo(httpServletRequest, user);

        return ResultUtil.getNoObjectInstance(ResultEnum.SUCCESS);
    }

    @DeleteMapping
    @ResponseBody
    public Result doDelete(HttpServletRequest httpServletRequest){
        httpServletRequest.getSession().removeAttribute("userId");
        return ResultUtil.getNoObjectInstance(ResultEnum.SUCCESS);
    }
}
